const { app, BrowserWindow, ipcMain, dialog, Menu, shell } = require('electron');
const path = require('path');
const fs = require('fs');
const https = require('https');
const os = require('os');

let mainWindow;
let aboutWindow;
let jdksData = null;

// 检测当前系统信息
function getCurrentSystemInfo() {
  const platform = os.platform();
  const arch = os.arch();

  let osType = 'windows';
  if (platform === 'darwin') {
    osType = 'macOS';
  } else if (platform === 'linux') {
    osType = 'linux';
  }

  let archType = 'x86_64';
  if (arch === 'arm64' || arch === 'arm') {
    archType = 'aarch64';
  }

  return { os: osType, arch: archType };
}

// 读取 jdks.json 文件
function loadJdksData() {
  try {
    const jdksPath = path.join(__dirname, 'jdks.json');
    const data = fs.readFileSync(jdksPath, 'utf8');
    jdksData = JSON.parse(data);
    console.log('JDK 数据加载成功');
    return true;
  } catch (error) {
    console.error('加载 JDK 数据失败:', error);
    return false;
  }
}

// 获取可用的选项
function getAvailableOptions() {
  if (!jdksData || !jdksData.jdks) return null;

  const options = {
    os: new Set(),
    arch: new Set(),
    versions: new Set(),
    vendors: new Set()
  };

  jdksData.jdks.forEach(jdk => {
    options.vendors.add(jdk.vendor);
    options.versions.add(jdk.jdk_version);

    if (jdk.packages) {
      jdk.packages.forEach(pkg => {
        options.os.add(pkg.os);
        options.arch.add(pkg.arch);
      });
    }
  });

  return {
    os: Array.from(options.os).sort(),
    arch: Array.from(options.arch).sort(),
    versions: Array.from(options.versions).sort((a, b) => parseFloat(b) - parseFloat(a)),
    vendors: Array.from(options.vendors).sort()
  };
}

// 根据选择查找匹配的包
function findMatchingPackage(os, arch, version, vendor) {
  console.log(`查找包: os=${os}, arch=${arch}, version=${version}, vendor=${vendor}`);

  if (!jdksData || !jdksData.jdks) {
    console.log('JDK 数据未加载');
    return null;
  }

  const matchingJdk = jdksData.jdks.find(jdk =>
    jdk.vendor === vendor &&
    jdk.jdk_version === version &&
    jdk.packages &&
    jdk.packages.some(pkg => pkg.os === os && pkg.arch === arch)
  );

  if (matchingJdk) {
    console.log(`找到匹配的 JDK: ${matchingJdk.vendor} ${matchingJdk.jdk_version}`);
    const packageInfo = matchingJdk.packages.find(pkg => pkg.os === os && pkg.arch === arch);
    console.log(`包信息: ${packageInfo.archive_file_name}`);
    return packageInfo;
  }

  console.log('未找到匹配的 JDK 包');
  // 调试信息：查找所有可能的匹配
  const possibleMatches = jdksData.jdks.filter(jdk =>
    jdk.vendor === vendor &&
    jdk.jdk_version === version
  );
  console.log(`找到 ${possibleMatches.length} 个匹配供应商和版本的 JDK`);

  possibleMatches.forEach(jdk => {
    if (jdk.packages) {
      const matchingPackages = jdk.packages.filter(pkg => pkg.os === os && pkg.arch === arch);
      console.log(`  - ${jdk.jdk_version}: ${matchingPackages.length} 个匹配的包`);
      matchingPackages.forEach(pkg => {
        console.log(`    * ${pkg.os}-${pkg.arch}: ${pkg.archive_file_name}`);
      });
    }
  });

  return null;
}

// 下载文件
function downloadFile(url, filePath, onProgress) {
  return new Promise((resolve, reject) => {
    const file = fs.createWriteStream(filePath);

    const request = https.get(url, (response) => {
      if (response.statusCode !== 200) {
        reject(new Error(`下载失败: ${response.statusCode}`));
        return;
      }

      const totalSize = parseInt(response.headers['content-length'], 10);
      let downloadedSize = 0;

      response.on('data', (chunk) => {
        downloadedSize += chunk.length;
        if (totalSize && onProgress) {
          const progress = (downloadedSize / totalSize) * 100;
          onProgress(progress, downloadedSize, totalSize);
        }
      });

      response.pipe(file);

      file.on('finish', () => {
        file.close();
        resolve();
      });
    });

    request.on('error', (err) => {
      fs.unlink(filePath, () => {});
      reject(err);
    });

    file.on('error', (err) => {
      fs.unlink(filePath, () => {});
      reject(err);
    });
  });
}

function createWindow() {
  mainWindow = new BrowserWindow({
    width: 500,
    height: 900,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true,
      preload: path.join(__dirname, 'preload.js')
    },
    icon: path.join(__dirname, 'assets', 'icon.png'),
    title: 'JDK 下载器',
    show: false // 先隐藏主窗口
  });

  mainWindow.loadFile('src/index.html');

  // 主窗口加载完成后显示
  mainWindow.once('ready-to-show', () => {
    mainWindow.show();
  });
}

// 创建关于窗口
function createAboutWindow() {
  aboutWindow = new BrowserWindow({
    width: 350,
    height: 650,
    resizable: false,
    minimizable: false,
    maximizable: false,
    alwaysOnTop: true,
    modal: true,
    parent: mainWindow,
    webPreferences: {
      nodeIntegration: false,
      contextIsolation: true
    },
    icon: path.join(__dirname, 'assets', 'gaochi_logo_128x128.png'),
    title: '关于 JDK 下载助手',
    show: false
  });

  // 读取logo图片并转换为base64
  let logoBase64 = '';
  try {
    const logoPath = path.join(__dirname, 'assets', 'gaochi_logo_128x128.png');
    const logoBuffer = fs.readFileSync(logoPath);
    logoBase64 = `data:image/png;base64,${logoBuffer.toString('base64')}`;
  } catch (error) {
    console.error('无法加载logo图片:', error);
    // 如果无法加载，使用一个简单的占位符
    logoBase64 = '';
  }

  // 创建关于页面的 HTML 内容
  const aboutHTML = `
    <!DOCTYPE html>
    <html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>关于 JDK 下载助手</title>
        <style>
            * {
                margin: 0;
                padding: 0;
                box-sizing: border-box;
            }
            html, body {
                font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
                background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
                margin: 0;
                padding: 20px;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                height: 100vh;
                color: #000;
                text-align: center;
                overflow: auto;
            }
            /* 隐藏滚动条但保持滚动功能 */
            ::-webkit-scrollbar {
                display: none;
            }
            html {
                scrollbar-width: none; /* Firefox */
                -ms-overflow-style: none; /* IE and Edge */
            }
            .logo {
                width: 80px;
                height: 80px;
                margin-bottom: 20px;
                border-radius: 12px;
                box-shadow: 0 4px 12px rgba(0,0,0,0.3);
            }
            .title {
                font-size: 24px;
                font-weight: bold;
                margin-bottom: 10px;
                text-shadow: 0 2px 4px rgba(0,0,0,0.3);
            }
            .version {
                font-size: 16px;
                margin-bottom: 15px;
                opacity: 0.9;
            }
            .description {
                font-size: 14px;
                margin-bottom: 25px;
                line-height: 1.6;
                opacity: 0.9;
            }
            .info {
                background: rgba(255,255,255,0.1);
                padding: 20px;
                border-radius: 12px;
                backdrop-filter: blur(10px);
                border: 1px solid rgba(255,255,255,0.2);
                width: 100%;
                max-width: 450px;
                margin-bottom: 25px;
            }
            .info-item {
                margin-bottom: 8px;
                font-size: 13px;
            }
            .info-label {
                font-weight: bold;
                color: #000;
            }
            .copyright {
                font-size: 12px;
                opacity: 0.7;
                margin-bottom: 25px;
            }
            .close-btn {
                background: linear-gradient(135deg, #28a745 0%, #20c997 100%);
                color: white;
                border: none;
                padding: 12px 30px;
                border-radius: 8px;
                font-size: 14px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                box-shadow: 0 4px 15px rgba(40, 167, 69, 0.3);
            }
            .close-btn:hover {
                transform: translateY(-2px);
                box-shadow: 0 8px 25px rgba(40, 167, 69, 0.4);
                background: linear-gradient(135deg, #20c997 0%, #28a745 100%);
            }
            .website-link {
                color: #87ceeb;
                text-decoration: none;
                cursor: pointer;
            }
            .website-link:hover {
                text-decoration: underline;
            }
        </style>
        <script>
            function openWebsite(url) {
                // 通过IPC调用主进程打开外部链接
                window.postMessage({ type: 'open-external', url: url }, '*');
            }
        </script>
    </head>
    <body>
        <img src="${logoBase64}" alt="高驰logo" class="logo">
        <div class="title">JDK下载助手</div>
        <div class="description">支持国产、苹果、微软Windows系统</div>

        <div class="info">
            <div class="info-item">
                <span class="info-label">开发者：</span>曾伟
            </div>
            <div class="info-item">
                <span class="info-label">电话：</span>18583638321
            </div>
            <div class="info-item">
                <span class="info-label">邮箱：</span>832192@qq.com
            </div>
            <div class="info-item">
                <span class="info-label">官网：</span><span class="website-link" onclick="openWebsite('https://www.xzgaochi.com/')">https://www.xzgaochi.com/</span>
            </div>
            
            <div class="info-item">
                四川天府高驰信息技术有限公司-研发创新中心
            </div>
        </div>
 
        <button class="close-btn" onclick="window.close()">我知道了</button>
    </body>
    </html>
  `;

  // 加载 HTML 内容
  aboutWindow.loadURL(`data:text/html;charset=utf-8,${encodeURIComponent(aboutHTML)}`);

  // 窗口加载完成后显示
  aboutWindow.once('ready-to-show', () => {
    aboutWindow.show();
  });

  // 窗口关闭时清理引用
  aboutWindow.on('closed', () => {
    aboutWindow = null;
  });
}

// 移除菜单栏
Menu.setApplicationMenu(null);

app.whenReady().then(() => {
  // 加载 JDK 数据
  if (!loadJdksData()) {
    dialog.showErrorBox('错误', '无法加载 JDK 配置文件，请检查 jdks.json 文件是否存在且格式正确。');
    app.quit();
    return;
  }

  // 创建主窗口（先隐藏）
  createWindow();

  // 显示关于窗口
  createAboutWindow();

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow();
    }
  });
});

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

// 获取指定供应商的可用操作系统
function getOSForVendor(selectedVendor) {
  if (!jdksData || !jdksData.jdks) return [];

  const osSet = new Set();
  jdksData.jdks.forEach(jdk => {
    if (jdk.vendor === selectedVendor && jdk.packages) {
      jdk.packages.forEach(pkg => {
        osSet.add(pkg.os);
      });
    }
  });

  return Array.from(osSet).sort();
}

// 获取指定供应商和操作系统的可用架构
function getArchitecturesForVendorOS(selectedVendor, selectedOS) {
  if (!jdksData || !jdksData.jdks) return [];

  const architectures = new Set();
  jdksData.jdks.forEach(jdk => {
    if (jdk.vendor === selectedVendor && jdk.packages) {
      jdk.packages.forEach(pkg => {
        if (pkg.os === selectedOS) {
          architectures.add(pkg.arch);
        }
      });
    }
  });

  return Array.from(architectures).sort();
}

// 获取指定操作系统和架构的可用供应商
function getVendorsForOSArch(selectedOS, selectedArch) {
  if (!jdksData || !jdksData.jdks) return [];

  const vendors = new Set();
  jdksData.jdks.forEach(jdk => {
    if (jdk.packages) {
      const hasMatchingPackage = jdk.packages.some(pkg =>
        pkg.os === selectedOS && pkg.arch === selectedArch
      );
      if (hasMatchingPackage) {
        vendors.add(jdk.vendor);
      }
    }
  });

  return Array.from(vendors).sort();
}

// 获取指定操作系统、架构和供应商的可用版本
function getVersionsForOSArchVendor(selectedOS, selectedArch, selectedVendor) {
  if (!jdksData || !jdksData.jdks) return [];

  const versions = new Set();
  jdksData.jdks.forEach(jdk => {
    if (jdk.vendor === selectedVendor && jdk.packages) {
      const hasMatchingPackage = jdk.packages.some(pkg =>
        pkg.os === selectedOS && pkg.arch === selectedArch
      );
      if (hasMatchingPackage) {
        versions.add(jdk.jdk_version);
      }
    }
  });

  return Array.from(versions).sort((a, b) => parseFloat(b) - parseFloat(a));
}

// 处理打开外部链接的消息
ipcMain.on('open-external-link', (event, url) => {
  shell.openExternal(url).catch(err => {
    console.error('无法打开外部链接:', err);
  });
});

// 处理取消下载的消息
ipcMain.on('cancel-download', (event) => {
  // 注意：由于使用简单的https.get()，我们无法中断正在进行的HTTP请求
  // 但我们可以通知前端清理UI状态
  console.log('收到取消下载请求');
  // 这里可以添加更多的清理逻辑，比如删除部分下载的文件等
});

// IPC 处理
ipcMain.handle('get-system-info', () => {
  return getCurrentSystemInfo();
});

ipcMain.handle('get-available-options', () => {
  return getAvailableOptions();
});

ipcMain.handle('get-os-for-vendor', (event, vendor) => {
  return getOSForVendor(vendor);
});

ipcMain.handle('get-architectures-for-vendor-os', (event, { vendor, os }) => {
  return getArchitecturesForVendorOS(vendor, os);
});

ipcMain.handle('get-vendors-for-os-arch', (event, { os, arch }) => {
  return getVendorsForOSArch(os, arch);
});

ipcMain.handle('get-versions-for-os-arch-vendor', (event, { os, arch, vendor }) => {
  return getVersionsForOSArchVendor(os, arch, vendor);
});

ipcMain.handle('download-jdk', async (event, { os, arch, version, vendor }) => {
  const packageInfo = findMatchingPackage(os, arch, version, vendor);

  if (!packageInfo) {
    throw new Error('未找到匹配的 JDK 包');
  }

  const fileName = packageInfo.archive_file_name;
  const downloadPath = path.join(__dirname, fileName);

  try {
    await downloadFile(packageInfo.url, downloadPath, (progress, downloaded, total) => {
      mainWindow.webContents.send('download-progress', {
        progress: Math.round(progress),
        downloaded,
        total,
        fileName
      });
    });

    return {
      success: true,
      filePath: downloadPath,
      fileName
    };
  } catch (error) {
    throw new Error(`下载失败: ${error.message}`);
  }
});
